<template>
  <div class="game-canvas-container">
    <div class="canvas-wrapper">
      <canvas
        ref="canvasRef"
        :width="canvasWidth"
        :height="canvasHeight"
        class="game-canvas"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
      ></canvas>
      
      <!-- 游戏状态覆盖层 -->
      <div v-if="gameStatus !== 'playing'" class="game-overlay">
        <div class="overlay-content">
          <h2 v-if="gameStatus === 'waiting'">等待游戏开始...</h2>
          <h2 v-else-if="gameStatus === 'finished'">游戏结束！</h2>
          <p v-if="winner">获胜者: {{ winner.nickname }}</p>
        </div>
      </div>
      
      <!-- 实时同步状态指示器 -->
      <div class="sync-indicator" :class="{ active: isSyncing }">
        <el-icon><Loading /></el-icon>
        <span>同步中...</span>
      </div>
      
      <!-- 实时同步状态指示器 -->
      <div class="sync-indicator" :class="{ active: isSyncing }">
        <el-icon><Loading /></el-icon>
        <span>同步中...</span>
      </div>
    </div>
    
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed, nextTick } from 'vue'
import { useGameStore } from '@/stores/game'
import { createSignalRService } from '@/services/socketService'
import { Brush, Delete, Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
// 测试/调试工具移除
import { AreaCalculator } from '@/utils/areaCalculator'

const props = defineProps({
  roomId: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['areaUpdated'])

const gameStore = useGameStore()

// 确保SignalR服务正确初始化
const signalRService = createSignalRService(gameStore)

// 画布相关
const canvasRef = ref(null)
const canvasWidth = 800
const canvasHeight = 600
const ctx = ref(null)
const isDrawing = ref(false)
const lastX = ref(0)
const lastY = ref(0)
const areaCalc = ref(null)
// 占用检测节流提示
let lastBlockedAt = 0
const BLOCK_HINT_INTERVAL = 800

// 工具设置
const currentTool = ref('brush')
const brushSize = ref(10)
const currentColor = ref('') // 颜色将由后端分配

// 撤销功能
const actionHistory = ref([])
const maxHistorySize = 50

// 同步状态
const isSyncing = ref(false)
const receivedActionsCount = ref(0)
const sentActionsCount = ref(0)
const lastSyncTime = ref(0)

// 游戏状态
const gameStatus = computed(() => gameStore.gameStatus)
const winner = computed(() => gameStore.winner)
const isConnected = computed(() => gameStore.isConnected)

// 计算属性
const canUndo = computed(() => actionHistory.value.length > 0)

// 触摸事件处理
let touchStartTime = 0
let lastTouchX = 0
let lastTouchY = 0

// 防抖处理
let paintDebounceTimer = null
const paintDebounceDelay = 16 // 约60fps

// 面积更新节流
let lastAreaSendAt = 0
const AREA_SEND_INTERVAL_MS = 500

onMounted(() => {
  console.log('GameCanvas mounted')
  console.log('SignalR服务状态:', signalRService.getConnectionStatus())
  console.log('游戏Store状态:', gameStore.isConnected)
  console.log('当前玩家信息:', gameStore.currentPlayer)
  console.log('房间ID:', props.roomId)
  
  initCanvas()
  setupSocketListeners()
  
  // 确保SignalR连接已建立
  if (!signalRService.getConnectionStatus()) {
    console.log('SignalR未连接，尝试连接...')
    signalRService.connect()
  }
  
  // 立即设置事件监听器，不延迟
  setupSocketListeners()
  
  // 监听当前玩家颜色变化
  watch(() => gameStore.currentPlayer?.brushColor, (newColor) => {
    console.log('监听到画笔颜色变化:', newColor)
    if (newColor && newColor !== currentColor.value) {
      currentColor.value = newColor
      console.log('画笔颜色已更新:', newColor)
      updateBrushStyle()
    }
  }, { immediate: true }) // 立即执行一次
  
  // 监听当前玩家变化
  watch(() => gameStore.currentPlayer, (newPlayer) => {
    console.log('监听到当前玩家变化:', newPlayer)
    if (newPlayer?.brushColor && newPlayer.brushColor !== currentColor.value) {
      currentColor.value = newPlayer.brushColor
      console.log('从玩家变化更新画笔颜色:', currentColor.value)
      updateBrushStyle()
    }
  }, { immediate: true }) // 立即执行一次
  
  // 监听玩家列表变化，确保颜色同步
  watch(() => gameStore.players, (newPlayers) => {
    console.log('监听到玩家列表变化:', newPlayers)
    const currentPlayer = gameStore.currentPlayer
    if (currentPlayer && currentPlayer.id) {
      const playerInList = newPlayers.find(p => p.id === currentPlayer.id)
      if (playerInList?.brushColor && playerInList.brushColor !== currentColor.value) {
        currentColor.value = playerInList.brushColor
        console.log('从玩家列表更新画笔颜色:', currentColor.value)
        updateBrushStyle()
      }
    }
  }, { deep: true, immediate: true })

  // 监听全局画笔大小（由房间页面控制），并应用到画布
  watch(() => gameStore.brushSize, (val) => {
    const num = typeof val === 'number' ? val : Number(val)
    if (!Number.isNaN(num) && num > 0) {
      brushSize.value = num
      updateBrushStyle()
    }
  }, { immediate: true })
})

onUnmounted(() => {
  console.log('GameCanvas unmounted')
  removeSocketListeners()
  
  // 清理防抖定时器
  if (paintDebounceTimer) {
    clearTimeout(paintDebounceTimer)
  }
})

function initCanvas() {
  console.log('初始化画布...')
  const canvas = canvasRef.value
  if (!canvas) {
    console.error('Canvas element not found')
    return
  }

  ctx.value = canvas.getContext('2d')
  if (!ctx.value) {
    console.error('Failed to get canvas context')
    return
  }
  // 初始化面积计算器
  areaCalc.value = new AreaCalculator(canvas)
  
  // 设置画布背景
  ctx.value.fillStyle = '#ffffff'
  ctx.value.fillRect(0, 0, canvasWidth, canvasHeight)
  
  // 设置画笔样式
  updateBrushStyle()
  
  console.log('画布初始化完成')
}

function setTool(tool) {
  currentTool.value = tool
  updateBrushStyle()
  console.log('工具已切换为:', tool)
}

function updateBrushStyle() {
  if (!ctx.value) return
  
  console.log('更新画笔样式:', {
    tool: currentTool.value,
    color: currentColor.value,
    size: brushSize.value
  })
  
  if (currentTool.value === 'brush') {
    // 如果没有颜色，使用默认颜色
    const brushColor = currentColor.value || '#1890ff'
    ctx.value.strokeStyle = brushColor
    ctx.value.fillStyle = brushColor
    console.log('设置画笔颜色为:', brushColor)
  } else if (currentTool.value === 'eraser') {
    ctx.value.strokeStyle = '#ffffff'
    ctx.value.fillStyle = '#ffffff'
  }
  
  ctx.value.lineWidth = brushSize.value
  ctx.value.lineCap = 'round'
  ctx.value.lineJoin = 'round'
  
  console.log('画笔样式已更新:', {
    tool: currentTool.value,
    color: currentColor.value,
    size: brushSize.value
  })
}

function startDrawing(event) {
  console.log('开始绘制', event.type)
  
  // 允许在任何游戏状态下绘制（用于测试）
  // if (gameStatus.value !== 'playing') return
  
  isDrawing.value = true
  const rect = canvasRef.value.getBoundingClientRect()
  lastX.value = event.clientX - rect.left
  lastY.value = event.clientY - rect.top
  
  updateBrushStyle()
  
  // 记录开始绘制
  if (currentTool.value === 'brush') {
    recordAction('start', lastX.value, lastY.value)
  }
  
  console.log('绘制开始位置:', { x: lastX.value, y: lastY.value })
}

function draw(event) {
  if (!isDrawing.value) return
  
  const rect = canvasRef.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  
  // 检查边界
  if (x < 0 || x >= canvasWidth || y < 0 || y >= canvasHeight) {
    return
  }
  
  // 根据工具类型绘制
  if (currentTool.value === 'brush') {
    drawBrush(x, y)
  } else if (currentTool.value === 'eraser') {
    // 禁止擦除（不改变已经上色的像素）
    maybeHintBlocked()
  }
  
  // 立即发送涂色动作，不使用防抖
  sendPaintAction(x, y, lastX.value, lastY.value)
  
  lastX.value = x
  lastY.value = y
}

function drawBrush(x, y) {
  if (!ctx.value) return
  // 使用裁剪绘制：只在未被上色的位置上画点，避免覆盖
  drawClippedSegment(lastX.value, lastY.value, x, y, brushSize.value, currentColor.value)
  
  // 记录绘制动作
  recordAction('draw', x, y)
  // 可能触发面积更新
  maybeSendAreaUpdate()
}

function drawEraser(x, y) {
  if (!ctx.value) return
  // 禁止擦除（不可修改已上色区域）
}

function stopDrawing() {
  console.log('停止绘制')
  isDrawing.value = false
  
  // 立即发送最后的涂色动作
  if (paintDebounceTimer) {
    clearTimeout(paintDebounceTimer)
    paintDebounceTimer = null
  }
  // 停止绘制后强制更新一次面积
  maybeSendAreaUpdate(true)
}

// 防抖发送涂色动作
function debouncedSendPaintAction(x, y) {
  if (paintDebounceTimer) {
    clearTimeout(paintDebounceTimer)
  }
  
  // 立即发送，不使用延迟
  sendPaintAction(x, y, lastX.value, lastY.value)
}

function recordAction(type, x, y) {
  const action = {
    type,
    x: Math.round(x),
    y: Math.round(y),
    color: currentColor.value,
    brushSize: brushSize.value,
    tool: currentTool.value,
    timestamp: Date.now()
  }
  
  actionHistory.value.push(action)
  
  // 限制历史记录大小
  if (actionHistory.value.length > maxHistorySize) {
    actionHistory.value.shift()
  }
}

function undoLastAction() {
  if (actionHistory.value.length === 0) return
  
  // 移除最后一个动作
  const lastAction = actionHistory.value.pop()
  
  // 重新绘制画布（简化版本）
  if (lastAction.type === 'erase') {
    // 恢复被擦除的区域
    restoreArea(lastAction.x, lastAction.y, lastAction.brushSize)
  } else if (lastAction.type === 'draw') {
    // 擦除绘制的区域
    eraseArea(lastAction.x, lastAction.y, lastAction.brushSize)
  }
}

function restoreArea(x, y, size) {
  if (!ctx.value) return
  
  // 这里应该恢复原始颜色，简化版本使用白色
  ctx.value.fillStyle = '#ffffff'
  ctx.value.beginPath()
  ctx.value.arc(x, y, size / 2, 0, 2 * Math.PI)
  ctx.value.fill()
}

function eraseArea(x, y, size) {
  if (!ctx.value) return
  
  ctx.value.fillStyle = '#ffffff'
  ctx.value.beginPath()
  ctx.value.arc(x, y, size / 2, 0, 2 * Math.PI)
  ctx.value.fill()
}

function sendPaintAction(x, y, fromX = undefined, fromY = undefined) {
  const paintData = {
    x: Math.round(x),
    y: Math.round(y),
    tool: currentTool.value,
    color: currentColor.value,
    brushSize: brushSize.value,
    fromX: fromX !== undefined ? Math.round(fromX) : undefined,
    fromY: fromY !== undefined ? Math.round(fromY) : undefined
  }
  
  console.log('准备发送涂色动作:', paintData)
  
  // 使用SignalR服务发送
  if (signalRService && signalRService.getConnectionStatus && signalRService.getConnectionStatus()) {
    // 获取当前玩家ID
    const currentPlayerId = gameStore.currentPlayer?.id || 'unknown'
    
    console.log('通过SignalR发送涂色动作:', {
      roomId: props.roomId,
      playerId: currentPlayerId,
      paintData
    })
    
    try {
      // 发送包含起始点的数据
      signalRService.sendPaintActionWithData(
        props.roomId,
        currentPlayerId,
        { ...paintData, playerId: currentPlayerId }
      )
      sentActionsCount.value++
      console.log('涂色动作发送成功')
    } catch (error) {
      console.error('发送涂色动作失败:', error)
      ElMessage.error('发送涂色动作失败')
    }
  } else {
    console.warn('SignalR服务未连接，跳过发送涂色动作')
    console.log('SignalR状态:', {
      service: !!signalRService,
      hasMethod: !!(signalRService && signalRService.getConnectionStatus),
      isConnected: signalRService ? signalRService.getConnectionStatus() : false
    })
  }
  
  // 记录动作到历史
  recordAction('paint', x, y)
}

function clearCanvas() {
  if (!ctx.value) return
  
  console.log('清空画布')
  
  // 记录清空动作
  recordAction('clear', 0, 0)
  
  ctx.value.fillStyle = '#ffffff'
  ctx.value.fillRect(0, 0, canvasWidth, canvasHeight)
  // 清空后更新面积
  maybeSendAreaUpdate(true)
  
  // 通知其他玩家画布已清空
  if (signalRService && signalRService.getConnectionStatus && signalRService.getConnectionStatus()) {
    const currentPlayerId = gameStore.currentPlayer?.id || 'unknown'
    signalRService.sendPaintAction(
      props.roomId,
      currentPlayerId,
      0, 0, '#ffffff', 0, 'clear'
    )
  }
}

// 触摸事件处理
function handleTouchStart(event) {
  event.preventDefault()
  console.log('触摸开始')
  
  const touch = event.touches[0]
  const rect = canvasRef.value.getBoundingClientRect()
  lastTouchX = touch.clientX - rect.left
  lastTouchY = touch.clientY - rect.top
  touchStartTime = Date.now()
  
  isDrawing.value = true
  updateBrushStyle()
  
  if (currentTool.value === 'brush') {
    recordAction('start', lastTouchX, lastTouchY)
  }
}

function handleTouchMove(event) {
  event.preventDefault()
  if (!isDrawing.value) return
  
  const touch = event.touches[0]
  const rect = canvasRef.value.getBoundingClientRect()
  const x = touch.clientX - rect.left
  const y = touch.clientY - rect.top
  
  if (x < 0 || x >= canvasWidth || y < 0 || y >= canvasHeight) {
    return
  }
  
  // 若目标像素已被上色（非白），禁止二次涂改
  if (currentTool.value === 'brush') {
    drawBrush(x, y)
  } else if (currentTool.value === 'eraser') {
    // 禁止擦除
  }
  
  debouncedSendPaintAction(x, y)
  // 触发面积更新（触摸）
  maybeSendAreaUpdate()
  
  lastTouchX = x
  lastTouchY = y
}

function handleTouchEnd(event) {
  event.preventDefault()
  console.log('触摸结束')
  isDrawing.value = false
}

// Socket事件监听
function setupSocketListeners() {
  console.log('设置Socket事件监听器')
  console.log('SignalR服务对象:', signalRService)
  console.log('SignalR连接状态:', signalRService.getConnectionStatus())
  
  // 监听涂色动作事件
  if (signalRService && signalRService.on) {
    // 先移除可能存在的监听器
    signalRService.off('PaintActionReceived', handlePaintActionReceived)
    
    // 重新添加监听器
    signalRService.on('PaintActionReceived', handlePaintActionReceived)
    console.log('PaintActionReceived事件监听器已设置')
  } else {
    console.error('SignalR服务不可用或缺少on方法')
    console.error('signalRService:', signalRService)
    console.error('signalRService.on:', signalRService?.on)
  }
}

function removeSocketListeners() {
  console.log('移除Socket事件监听器')
  
  if (signalRService && signalRService.off) {
    signalRService.off('PaintActionReceived', handlePaintActionReceived)
    console.log('PaintActionReceived事件监听器已移除')
  }
}

// 处理从其他玩家收到的涂色动作
function handlePaintActionReceived(paintData) {
  console.log('收到其他玩家的涂色动作:', paintData)
  console.log('paintData类型:', typeof paintData)
  console.log('paintData键:', Object.keys(paintData || {}))
  console.log('paintData完整内容:', JSON.stringify(paintData, null, 2))
  receivedActionsCount.value++
  
  if (!ctx.value) {
    console.error('Canvas context不可用')
    return
  }
  
  // 获取当前玩家ID
  const currentPlayerId = gameStore.currentPlayer?.id
  console.log('当前玩家ID:', currentPlayerId)
  console.log('发送者玩家ID:', paintData?.playerId)
  
  // 检查是否是自己的涂色动作（使用正确的键名）
  if (paintData.playerId === currentPlayerId) {
    console.log('收到自己的涂色动作，继续处理以支持同步验证')
  } else {
    console.log('收到其他玩家的涂色动作')
  }
  
  // 使用正确的键名（后端发送的是小写）
  const { x, y, tool, color, brushSize, fromX, fromY } = paintData
  
  console.log('绘制其他玩家的动作:', { x, y, fromX, fromY, tool, color, brushSize })
  
  // 显示同步状态
  isSyncing.value = true
  lastSyncTime.value = Date.now()
  
  // 根据工具类型绘制
  if (tool === 'brush') {
    if (fromX !== undefined && fromY !== undefined) {
      // 使用裁剪绘制，避免覆盖已上色像素
      drawClippedSegment(fromX, fromY, x, y, brushSize, color)
    } else {
      // 单点绘制（仅在未上色时画）
      drawDotIfUnpainted(x, y, brushSize, color)
    }
  } else if (tool === 'eraser') {
    // 禁止擦除
    console.log('忽略橡皮擦动作（不可覆盖）')
  } else if (tool === 'clear') {
    // 处理清空画布动作
    ctx.value.fillStyle = '#ffffff'
    ctx.value.fillRect(0, 0, canvasWidth, canvasHeight)
    console.log('画布已清空')
  }
  
  // 延迟隐藏同步状态
  setTimeout(() => {
    isSyncing.value = false
  }, 500)
  
  // 触发面积更新事件
  emit('areaUpdated', { x, y, color, brushSize })
  // 其他玩家绘制也可能影响我的面积，尝试节流更新
  maybeSendAreaUpdate()
}

// 计算并广播面积（节流）
function maybeSendAreaUpdate(force = false) {
  if (!areaCalc.value || !signalRService || !signalRService.getConnectionStatus || !signalRService.getConnectionStatus()) return
  const now = Date.now()
  if (!force && now - lastAreaSendAt < AREA_SEND_INTERVAL_MS) return
  const playerId = gameStore.currentPlayer?.id
  const colorHex = (currentTool.value === 'eraser' ? currentColor.value : currentColor.value || '').toLowerCase()
  if (!playerId || !colorHex) return
  try {
    const area = areaCalc.value.calculateAreaByColor(colorHex)
    // 本地立即更新以获得更流畅的体验
    gameStore.updatePlayerArea(playerId, area)
    // 广播到房间
    signalRService.updateArea(props.roomId, playerId, area)
    lastAreaSendAt = now
  } catch (e) {
    console.warn('面积计算或广播失败:', e)
  }
}

// 工具：判断目标像素是否已被上色（非白）
function isPaintBlocked(x, y) {
  if (!ctx.value) return false
  const pixel = ctx.value.getImageData(Math.round(x), Math.round(y), 1, 1).data
  const r = pixel[0], g = pixel[1], b = pixel[2], a = pixel[3]
  // 未上色：透明 或 纯白
  const isUnpainted = (a === 0) || (r === 255 && g === 255 && b === 255)
  return !isUnpainted
}

function drawDotIfUnpainted(x, y, size, color) {
  if (!ctx.value) return
  if (isPaintBlocked(x, y)) return
  ctx.value.fillStyle = color
  ctx.value.beginPath()
  ctx.value.arc(x, y, size / 2, 0, 2 * Math.PI)
  ctx.value.fill()
}

function drawClippedSegment(fromX, fromY, toX, toY, size, color) {
  if (!ctx.value) return
  // 计算裁剪区域
  const half = size / 2 + 2
  const minX = Math.max(0, Math.floor(Math.min(fromX, toX) - half))
  const minY = Math.max(0, Math.floor(Math.min(fromY, toY) - half))
  const maxX = Math.min(canvasWidth, Math.ceil(Math.max(fromX, toX) + half))
  const maxY = Math.min(canvasHeight, Math.ceil(Math.max(fromY, toY) + half))
  const w = Math.max(1, maxX - minX)
  const h = Math.max(1, maxY - minY)

  // 创建离屏画布
  const off = document.createElement('canvas')
  off.width = w
  off.height = h
  const octx = off.getContext('2d')
  if (!octx) return

  // 在离屏上绘制完整的平滑线段
  octx.strokeStyle = color
  octx.lineWidth = size
  octx.lineCap = 'round'
  octx.lineJoin = 'round'
  octx.beginPath()
  octx.moveTo(fromX - minX, fromY - minY)
  octx.lineTo(toX - minX, toY - minY)
  octx.stroke()

  // 获取主画布区域与离屏像素
  const region = ctx.value.getImageData(minX, minY, w, h)
  const dest = region.data
  const src = octx.getImageData(0, 0, w, h).data

  // 解析颜色
  const { r: cr, g: cg, b: cb } = parseHexColor(color)

  // 将离屏线段拷贝到“未上色”像素上，直接写入不透明颜色，避免白色描边
  for (let i = 0; i < dest.length; i += 4) {
    const aSrc = src[i + 3]
    if (aSrc === 0) continue
    const rDst = dest[i]
    const gDst = dest[i + 1]
    const bDst = dest[i + 2]
    const aDst = dest[i + 3]
    const isUnpainted = (aDst === 0) || (rDst === 255 && gDst === 255 && bDst === 255)
    if (isUnpainted) {
      dest[i] = cr
      dest[i + 1] = cg
      dest[i + 2] = cb
      dest[i + 3] = 255
    }
  }

  // 回写至主画布
  ctx.value.putImageData(region, minX, minY)
}

function parseHexColor(hex) {
  if (!hex) return { r: 0, g: 0, b: 0 }
  let s = String(hex).trim()
  if (s[0] === '#') s = s.slice(1)
  if (s.length === 3) {
    s = s.split('').map(c => c + c).join('')
  }
  const num = parseInt(s, 16)
  return {
    r: (num >> 16) & 0xff,
    g: (num >> 8) & 0xff,
    b: num & 0xff
  }
}

function maybeHintBlocked() {
  const now = Date.now()
  if (now - lastBlockedAt < BLOCK_HINT_INTERVAL) return
  lastBlockedAt = now
  // 轻量提示可在此添加，如需要：
  // ElMessage.warning('该区域已被占领，无法涂改')
}

// 同步画布状态
function syncCanvasState() {
  console.log('同步画布状态...')
  
  if (!ctx.value) {
    ElMessage.warning('画布未初始化')
    return
  }
  
  // 获取画布数据
  const imageData = ctx.value.getImageData(0, 0, canvasWidth, canvasHeight)
  const data = imageData.data
  
  // 计算非白色像素数量（简化版本）
  let coloredPixels = 0
  for (let i = 0; i < data.length; i += 4) {
    const r = data[i]
    const g = data[i + 1]
    const b = data[i + 2]
    
    // 如果不是白色像素
    if (r !== 255 || g !== 255 || b !== 255) {
      coloredPixels++
    }
  }
  
  console.log('画布状态同步完成，彩色像素数量:', coloredPixels)
  ElMessage.success('画布状态已同步')
}

// 监听画笔大小变化
watch(brushSize, () => {
  updateBrushStyle()
})

// 监听颜色变化
watch(currentColor, () => {
  updateBrushStyle()
})

// 监听工具变化
watch(currentTool, () => {
  updateBrushStyle()
})

// 暴露方法给父组件
defineExpose({
  clearCanvas,
  updateBrushStyle,
  setTool,
  undoLastAction,
  clearCanvas,
  updateBrushStyle,
  setTool,
  undoLastAction
})

// 测试同步功能
// 测试/调试相关逻辑已移除
</script>

<style scoped>
.game-canvas-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 20px;
}

.canvas-wrapper {
  position: relative;
  border: 2px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.game-canvas {
  display: block;
  cursor: crosshair;
  touch-action: none;
}

.game-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.sync-indicator {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px 12px;
  border-radius: 20px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 5px;
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
}

.sync-indicator.active {
  opacity: 1;
}

.sync-indicator .el-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.overlay-content {
  text-align: center;
}

.overlay-content h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
}

.overlay-content p {
  margin: 0;
  font-size: 18px;
}

.sync-indicator {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px 12px;
  border-radius: 20px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 5px;
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
}

.sync-indicator.active {
  opacity: 1;
}

.sync-indicator .el-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.canvas-controls {
  display: flex;
  gap: 20px;
  align-items: center;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  flex-wrap: wrap;
}

.control-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
  align-items: center;
}

.control-group label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.color-display {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  border: 2px solid #ddd;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: default;
}

.color-note {
  color: #666;
  font-size: 11px;
  margin-top: 4px;
  text-align: center;
}

.tool-buttons {
  display: flex;
  gap: 10px;
}

.debug-info {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}

.debug-info p {
  margin: 2px 0;
}

.color-debug-info {
  margin-top: 10px;
  padding: 5px;
  background: #e0e0e0;
  border-radius: 4px;
  font-size: 12px;
  color: #333;
}

.color-debug-info h4 {
  margin-top: 0;
  margin-bottom: 5px;
  font-size: 14px;
  color: #555;
}

.color-preview {
  display: inline-block;
  width: 15px;
  height: 15px;
  border-radius: 50%;
  margin-right: 5px;
  vertical-align: middle;
}

.debug-buttons {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}

@media (max-width: 768px) {
  .canvas-controls {
    flex-direction: column;
    gap: 15px;
  }
  
  .game-canvas {
    width: 100%;
    height: auto;
  }
}
</style>
